package spring.framework.beans.factory.support;


import spring.framework.beans.BeansException;
import spring.framework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * @author fun.pengzh
 * @class spring.framework.beans.factory.support.AbstractAutoWireCapableBeanFactory
 * @desc 获取构造器 根据构造函数的类型推断
 * @since 2021-09-18
 */
public abstract class AbstractAutoWireCapableBeanFactory extends AbstractBeanFactory {

    private InstantiationStategy instantiationStategy = new CglibSubclassInstantiationStategy();

    protected abstract BeanDefinition getBeanDefinition(String beanName);

    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createBeanInstance(beanDefinition, beanName, args);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
        return bean;
    }

    protected Object createBeanInstance(BeanDefinition beanDefinition, String beanName, Object[] args) throws Exception {
        final Class beanClass = beanDefinition.getBeanClass();
        final Constructor[] constructors = beanClass.getConstructors();
        Constructor realConstructor = null;
        for (Constructor constructor : constructors) {
            if (null != args && constructor.getParameterTypes().length == args.length) {
                realConstructor = constructor;
                break;
            }
        }
        return getInstantiationStategy().instantiate(beanDefinition, beanName, realConstructor, args);
    }

    public InstantiationStategy getInstantiationStategy() {
        return instantiationStategy;
    }

    public void setInstantiationStategy(InstantiationStategy instantiationStategy) {
        this.instantiationStategy = instantiationStategy;
    }

}
